<template>
  <div>
    <!--搜索查询-->
    <el-row>
      <!-- <el-col :span="">&nbsp;</el-col> -->
      <el-col :span="4">
        <el-input v-model="searchForm.roleName" size="mini" clearable placeholder="请输入角色名称"></el-input>
      </el-col>
      <el-col :span="2">
      <el-button type="primary" size="mini" @click="search()" icon="el-icon-search">搜索</el-button>
      </el-col>
      <!-- v-has="'role:insert'" -->
      <el-col :span="2">
        <el-button type="primary" size="mini" @click="handlerAdd()"  icon="el-icon-circle-plus">添加</el-button>
      </el-col>
      <!-- v-has="'role:flush'" -->
      <el-col :span="2">
        <el-button type="primary" size="mini" @click="flush()"  icon="el-icon-refresh">刷新</el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="roleName" label="角色名称" align="center" width="150">
        </el-table-column>
        <el-table-column prop="remark" label="描述" align="center" width="200">
        </el-table-column>
        <el-table-column prop="status" :formatter="zhFormat" width="150" label="角色状态">
        </el-table-column>
        <!-- <el-table-column
          prop="delFlag"
          :formatter="delFormat"
          width="150"
          label="删除状态"
        > 
        </el-table-column>-->
        <el-table-column label="操作" fixed="right" align="center">
          <template slot-scope="scope">
            <!-- v-has="'role:impower'" -->
            <el-button size="mini" type="primary"  @click="showRoleList(scope.$index, scope.row)">角色授权</el-button>
            <!-- v-has="'role:update'" -->
            <el-button size="mini"  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <!-- v-has="'role:delete'" -->
            <el-button size="mini" type="danger"  @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <el-row>
      <!--角色添加-->
      <el-dialog :title="title" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
            <el-input v-model="form.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="remark" :label-width="formLabelWidth">
            <el-input v-model="form.remark" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色状态" prop="status" :label-width="formLabelWidth">
            <el-select v-model="form.status" placeholder="请选角色状态">
              <el-option label="正常" value="0"></el-option>
              <el-option label="禁用" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
      </el-dialog>
    </el-row>

    <el-row>
      <!--更新对话框-->
      <el-dialog :title="title" :visible.sync="dialogFormVisible2">
        <el-form :model="form2" :rules="rules" ref="form2">
          <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
            <el-input v-model="form2.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="remark" :label-width="formLabelWidth">
            <el-input v-model="form2.remark" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色状态" prop="status" :label-width="formLabelWidth">
            <el-select v-model="form2.status" placeholder="请选角色状态">
              <el-option label="正常" value="0"></el-option>
              <el-option label="禁用" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="quxiao()">取 消</el-button>
          <el-button type="primary" @click="submitForm2('form2')">确 定</el-button>
        </div>
      </el-dialog>
    </el-row>

    <el-row>
      <!--分页插件-->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[2, 3, 5, 10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-row>

    <el-row>
      <!--角色授权弹出框-->
      <el-dialog title="权限菜单" :visible.sync="menuTreeVisible">
        <el-tree :data="data"
                 :props="defaultProps"
                 node-key="menuId"
                 show-checkbox
                 check-strictly
                 ref="menuTree"
                 :default-checked-keys="nodeChecked"
                 default-expand-all>
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addPosAndMenu()">确 定</el-button>
        </div>
        <!-- :check-strictly="true" -->
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: [], //权限树数组对象
      defaultProps: {
        //父对象传值
        children: "children",
        label: "menuName",
      },
      nodeChecked: [], //勾选项目数组对象(数组元素是要勾选节点的key值)
      roleId: 0, //因为角色ID在不同的js方法种使用，定义为全局的
      tableData: [],
      title: "角色添加", //弹出对话框标题
      dialogFormVisible: false, //是否显示添加更新对话框  默认是不显示
      dialogFormVisible2: false,
      form: { roleName: "", remark: "", status: "0" }, //form表单对象
      form2:{},
      currentPage: 1, //页码 第几页
      pageSize: 5, //每页显示数量
      total: 100, //总条数
      searchForm: { roleName: "" }, //搜索form表单
      menuTreeVisible: false, //权限树是否显示
      formLabelWidth: "120px",
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        remark: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          // {
          //   min: 3,
          //   max: 50,
          //   message: "长度在 2 到 50 个字符",
          //   trigger: "blur",
          // },
        ],
        status: [
          { required: true, message: "请选择角色状态", trigger: "change" },
        ],
      },
    };
  },
  created() {
    //初始化方法 类似于jquery  $({})
    this.loadData();
  },
  //所有函数
  methods: {
    //加载数据
    loadData(){
      this.$http.post("/system/api/RoleController/selectAll?currentPage="+this.currentPage+"&pageSize="+this.pageSize,this.searchForm).then(resp=>{
        this.tableData=resp.data.data.list;
        this.total=resp.data.data.total;
      })
    },
    //处理更新
    handleEdit(index, row) {
      var _this = this;
      //row  当前行数据 如果是第一行  row = {deptId:1,deptName:'管理部'把一行数据赋值给form赋值,description:'店长的事',status:1}
      this.form2=row
      //显示对话框
      _this.dialogFormVisible2 = true;
      //指定对话框标题
      _this.title = "角色更新";
      //把一行数据赋值给form赋值
      _this.form = row;
      //防止修改框内容改变时直接改变当前行中的内容
      let copy = JSON.parse(JSON.stringify(row));
      _this.form = copy;
      //把数字1变为字符串1
      _this.form.status = row.status + "";
    },
    //处理添加
    handlerAdd() {
      //显示对话框
      this.dialogFormVisible = true;
      //指定对话框标题
      this.title = "角色添加";
      //让form表单重新赋空值
      this.form = {};
    },
    //处理删除
    handleDelete(row) {
      this.$http.post("/system/api/RoleController/delete?roleId="+row.roleId).then(resp=>{
       // console.log(row)
        if ((resp.data.code==200)){
          this.$message.success("删除成功");
        }
        this.loadData();
      })
    },
    zhFormat(row, column, cellValue, index) {
      //row当前行数据
      //column 列名称
      //cellValue 列的值
      //index 下标
      //alert(cellValue);
      return cellValue == 0 ? "正常" : "禁用";
    },
    delFormat(row, column, cellValue, index) {
      //row当前行数据
      //column 列名称
      //cellValue 列的值
      //index 下标
      //alert(cellValue);
      return cellValue == 0 ? "存在" : "消失了";
    },
    //处理每页数量发生变化
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      //让每页数量发生变化
      this.pageSize = val;
      //重载数据
      this.loadData();
    },
    //处理当前页变化
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      //让每页数量发生变化
      this.currentPage = val;
      //重载数据
      this.loadData();
    },
    //查询
    search() {
      this.currentPage = 1;
      this.loadData();
    },
    //刷新
    flush() {
      location.reload();
    },
    //取消按钮
    dialogFormVisiblExit() {
      this.form = "";
      this.dialogFormVisibleAdd = false;
    },
    //角色授权
    showRoleList(index, row) {
      //弹出框，显示权限树，根据该角色对应的权限，让权限树默认勾选响应的值
      //给角色ID复制
      //alert(JSON.stringify(row));
      this.roleId = row.roleId;
      //根据角色ID查出权限菜单ID，赋值给nodeChecked
      var _this = this;
      //初始化数据,把菜单树数据加载
      this.$http.get("/system/api/RoleController/queryAllTreeData").then(function (response) {
        let tmpData = response.data.data;
        console.log(response.data.data)
        // _this.data=response.data.data;
        //查询并给勾选项赋值
        _this.$http
          .get("/system/api/RoleController/queryMenusByRoleId?roleId=" + _this.roleId)
          .then(function (response) {
            console.log(response.data.data)
            //默认出树数据
            _this.data = tmpData;
            //默认勾选项
            _this.nodeChecked = response.data.data;
          });
      });

      //显示权限菜单对话框
      this.menuTreeVisible = true;
    },
    //添加角色(职位)和权限关联
    addPosAndMenu() {
      //console.log(this.$refs.menuTree.getCheckedNodes())
      //获取重新选中的节点
      let nodes = this.$refs.menuTree.getCheckedNodes(false, true).map(node => {
        return node.menuId;
      });
      //alert(nodes)
      //判断至少选中一个节点
      if (nodes.length < 1) {
        this.$message.error("至少选中一个节点");
        return; // 让代码终止运行
      }
      let tempMenuIds = "";
      //循环遍历
      for (var i = 0; i < nodes.length; i++) {
        tempMenuIds += nodes[i] + ",";
      }
      //tempMenuIds="100,101,102,200,201,"  拼接后最后加,  去掉最后一个逗号
      tempMenuIds = tempMenuIds.substr(0, tempMenuIds.length - 1);
      // alert(tempMenuIds)
      //tempMenuIds="100,101,102,200,201"
      //alert("当前角色为：" +this.roleId +"，该角色对应新的权限ID为：" +tempMenuIds);
      var _this = this;
      //执行后台添加方法
      this.$http
        .get(
          "/system/api/RoleController/batchInsertRoleMenu?roleId=" +
          this.roleId +
          "&menuIds=" +
          tempMenuIds
        )
        .then(function (response) {
          //console.log(response);
          //alert(JSON.stringify(response));
          if (response.data.code == 2000) {
            //提示成功
            _this.$message({
              type: "success",
              message: "授权成功!",
            });
            //关闭弹框
            _this.menuTreeVisible = false;
            //重新加载数据
            _this.loadData();
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message.error("你错了。。。");
        });
    },
    quxiao(){
      this.loadData();
      this.dialogFormVisible2=false;

    },
    //提交添加表单
    submitForm() {
      console.log(this.form)
      this.$http.post("/system/api/RoleController/insert",this.form).then(resp=>{
        if (resp.data.code==200){
          this.dialogFormVisible=false;
          this.$message.success("添加成功");
        }else if(resp.data.code==4001){
          this.$message.error("权限不足");
        }
        this.loadData();
      })
    },

    submitForm2(){
      console.log(this.form2)
      this.$http.post("/system/api//RoleController/update",this.form2).then(resp=>{
        if (resp.data.code==200){
          this.dialogFormVisible2=false;
          this.$message.success("编辑成功");
        }
        this.loadData();
      })
    }
  },
};
</script>
<style>
</style>
